"use client"

import { useState, useEffect, useCallback, useRef, useReducer, useMemo } from 'react';
import { 
  File, 
  Inbox, 
  Send, 
  Trash2, 
  Plus,
  RefreshCw,
  Loader2,
  Mail,
  Paperclip,
  AlertCircle,
  CheckCircle,
  Info,
  X,
  Upload,
  Sparkles,
  RotateCcw,
  Trash
} from "lucide-react"
import DOMPurify from 'dompurify';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';

import { emailMessagesAPI, emailAccountsAPI, aiPromptsAPI, type EmailMessage, type EmailAccount, type EmailFolder } from '@/lib/apiClient';
import { generateEmailSummary, isAIConfigured } from '@/lib/ai-helpers';

// 使用 useReducer 统一管理状态
type State = {
  accounts: EmailAccount[];
  selectedAccount: string;
  folders: EmailFolder[];
  selectedFolder: string;
  messages: EmailMessage[];
  selectedMessage: EmailMessage | null;
  folder: string;
  search: string;
  currentPage: number;
  hasMore: boolean;
  loading: {
    accounts: boolean;
    folders: boolean;
    messages: boolean;
    moreMessages: boolean;
    fetching: boolean;
    sendingEmail: boolean;
    aiSummarizing: boolean;
  };
  error: string | null;
  fetchMessage: { type: 'success' | 'error' | 'info'; text: string } | null;
};

type Action =
  | { type: 'SET_ACCOUNTS'; payload: EmailAccount[] }
  | { type: 'SET_FOLDERS'; payload: EmailFolder[] }
  | { type: 'SET_SELECTED_FOLDER'; payload: string }
  | { type: 'SET_MESSAGES'; payload: { messages: EmailMessage[]; append: boolean } }
  | { type: 'SET_SELECTED_MESSAGE'; payload: EmailMessage | null }
  | { type: 'SET_LOADING'; payload: { key: keyof State['loading']; value: boolean } }
  | { type: 'SET_FETCH_MESSAGE'; payload: State['fetchMessage'] }
  | { type: 'SET_FOLDER'; payload: string }
  | { type: 'SET_SEARCH'; payload: string }
  | { type: 'SET_SELECTED_ACCOUNT'; payload: string }
  | { type: 'SET_PAGINATION'; payload: { currentPage: number; hasMore: boolean } }
  | { type: 'UPDATE_MESSAGE'; payload: EmailMessage };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'SET_ACCOUNTS':
      return { ...state, accounts: action.payload };
    case 'SET_FOLDERS':
      return { ...state, folders: action.payload };
    case 'SET_SELECTED_FOLDER':
      return { ...state, selectedFolder: action.payload, folder: action.payload };
    case 'SET_MESSAGES':
      return {
        ...state,
        messages: action.payload.append 
          ? [...state.messages, ...action.payload.messages]
          : action.payload.messages
      };
    case 'SET_SELECTED_MESSAGE':
      return { ...state, selectedMessage: action.payload };
    case 'SET_LOADING':
      return {
        ...state,
        loading: { ...state.loading, [action.payload.key]: action.payload.value }
      };
    case 'SET_FETCH_MESSAGE':
      return { ...state, fetchMessage: action.payload };
    case 'SET_FOLDER':
      return { ...state, folder: action.payload };
    case 'SET_SEARCH':
      return { ...state, search: action.payload };
    case 'SET_SELECTED_ACCOUNT':
      return { ...state, selectedAccount: action.payload };
    case 'SET_PAGINATION':
      return { 
        ...state, 
        currentPage: action.payload.currentPage,
        hasMore: action.payload.hasMore 
      };
    case 'UPDATE_MESSAGE':
      return {
        ...state,
        messages: state.messages.map(m => 
          m.id === action.payload.id ? action.payload : m
        ),
        selectedMessage: state.selectedMessage?.id === action.payload.id 
          ? action.payload 
          : state.selectedMessage
      };
    default:
      return state;
  }
}

const initialState: State = {
  accounts: [],
  selectedAccount: '',
  folders: [],
  selectedFolder: 'inbox',
  messages: [],
  selectedMessage: null,
  folder: 'inbox',
  search: '',
  currentPage: 1,
  hasMore: true,
  loading: {
    accounts: false,
    folders: false,
    messages: false,
    moreMessages: false,
    fetching: false,
    sendingEmail: false,
    aiSummarizing: false,
  },
  error: null,
  fetchMessage: null,
};

/**
 * 现代化邮件查看器页面
 * 使用简单的三栏布局
 */
export default function EmailViewer() {
  const [state, dispatch] = useReducer(reducer, initialState);
  const [isComposeOpen, setIsComposeOpen] = useState(false);
  const [composeData, setComposeData] = useState({
    to: '',
    cc: '',
    bcc: '',
    subject: '',
    body: '',
    body_html: '',
    isHtml: false,
    attachments: [] as File[]
  });
  const [aiSummary, setAiSummary] = useState<string>('');
  const [showAiSummary, setShowAiSummary] = useState(false);
  
  // 使用 Ref 来避免将 isFetching 加入 useCallback 依赖
  const isFetchingRef = useRef(false);

  // 消息提示函数
  const showFetchMessage = useCallback((type: 'success' | 'error' | 'info', text: string) => {
    dispatch({ type: 'SET_FETCH_MESSAGE', payload: { type, text } });
    setTimeout(() => dispatch({ type: 'SET_FETCH_MESSAGE', payload: null }), 5000); // 5秒后自动消失
  }, []);

  // AI总结函数
  const handleAiSummary = useCallback(async () => {
    if (!state.selectedMessage) return;
    
    try {
      dispatch({ type: 'SET_LOADING', payload: { key: 'aiSummarizing', value: true } });
      
      // 首先检查邮件是否已有AI总结
      if (state.selectedMessage.ai_summary) {
        setAiSummary(state.selectedMessage.ai_summary);
        setShowAiSummary(true);
        showFetchMessage('success', 'AI总结已存在');
        return;
      }
      
      // 检查AI是否已配置
      if (!isAIConfigured()) {
        showFetchMessage('error', '请先在设置中配置AI服务（阿里云百炼、DeepSeek或Ollama）');
        return;
      }
      
      // 准备邮件内容
      const emailContent = state.selectedMessage.body_text || 
        (state.selectedMessage.body_html ? 
          state.selectedMessage.body_html.replace(/<[^>]*>/g, '') : '');
      
      if (!emailContent.trim()) {
        showFetchMessage('error', '邮件内容为空，无法生成总结');
        return;
      }
      
      // 获取提示词配置
      const promptConfig = await aiPromptsAPI.getByModule('email');
      const promptTemplate = promptConfig.prompt.prompt_template;
      
      // 使用统一函数生成总结
      const summary = await generateEmailSummary(
        state.selectedMessage.subject || '',
        state.selectedMessage.sender || '',
        emailContent,
        promptTemplate
      );
      
      setAiSummary(summary);
      setShowAiSummary(true);
      
      // 更新本地邮件对象
      dispatch({ 
        type: 'UPDATE_MESSAGE', 
        payload: { 
          ...state.selectedMessage, 
          ai_summary: summary 
        } 
      });
      
      // 保存到数据库
      try {
        await emailMessagesAPI.update(state.selectedMessage.id, { ai_summary: summary });
      } catch (error) {
        console.error('保存AI总结到数据库失败:', error);
      }
      
      showFetchMessage('success', 'AI总结生成成功');
      
    } catch (error) {
      console.error('AI总结失败:', error);
      
      let errorMessage = 'AI总结失败';
      if (error instanceof Error) {
        errorMessage = error.message;
      }
      
      showFetchMessage('error', errorMessage);
    } finally {
      dispatch({ type: 'SET_LOADING', payload: { key: 'aiSummarizing', value: false } });
    }
  }, [state.selectedMessage, showFetchMessage]);

  // 重新生成AI总结
  const handleRegenerateSummary = useCallback(async () => {
    if (!state.selectedMessage) return;
    
    try {
      dispatch({ type: 'SET_LOADING', payload: { key: 'aiSummarizing', value: true } });
      
      // 检查AI是否已配置
      if (!isAIConfigured()) {
        showFetchMessage('error', '请先在设置中配置AI服务（阿里云百炼、DeepSeek或Ollama）');
        return;
      }
      
      // 准备邮件内容
      const emailContent = state.selectedMessage.body_text || 
        (state.selectedMessage.body_html ? 
          state.selectedMessage.body_html.replace(/<[^>]*>/g, '') : '');
      
      if (!emailContent.trim()) {
        showFetchMessage('error', '邮件内容为空，无法生成总结');
        return;
      }
      
      // 获取提示词配置
      const promptConfig = await aiPromptsAPI.getByModule('email');
      const promptTemplate = promptConfig.prompt.prompt_template;
      
      // 使用统一函数生成总结
      const summary = await generateEmailSummary(
        state.selectedMessage.subject || '',
        state.selectedMessage.sender || '',
        emailContent,
        promptTemplate
      );
      
      setAiSummary(summary);
      
      // 更新本地邮件对象
      dispatch({ 
        type: 'UPDATE_MESSAGE', 
        payload: { 
          ...state.selectedMessage, 
          ai_summary: summary 
        } 
      });
      
      // 保存到数据库
      try {
        await emailMessagesAPI.update(state.selectedMessage.id, { ai_summary: summary });
      } catch (error) {
        console.error('保存AI总结到数据库失败:', error);
      }
      
      showFetchMessage('success', 'AI总结重新生成成功');
      
    } catch (error) {
      console.error('重新生成AI总结失败:', error);
      showFetchMessage('error', `重新生成失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      dispatch({ type: 'SET_LOADING', payload: { key: 'aiSummarizing', value: false } });
    }
  }, [state.selectedMessage, showFetchMessage]);

  // 清空AI总结
  const handleClearSummary = useCallback(async () => {
    if (!state.selectedMessage) return;
    
    try {
      // 清空本地状态
      setAiSummary('');
      
      // 更新本地邮件对象
      dispatch({ 
        type: 'UPDATE_MESSAGE', 
        payload: { 
          ...state.selectedMessage, 
          ai_summary: undefined 
        } 
      });
      
      // 清空数据库中的总结
      try {
        await emailMessagesAPI.update(state.selectedMessage.id, { ai_summary: '' });
        showFetchMessage('success', 'AI总结已清空');
      } catch (error) {
        console.error('清空AI总结失败:', error);
        showFetchMessage('error', '清空AI总结失败');
      }
      
    } catch (error) {
      console.error('清空AI总结失败:', error);
      showFetchMessage('error', '清空AI总结失败');
    }
  }, [state.selectedMessage, showFetchMessage]);

  const loadAccounts = useCallback(async () => {
    try {
      dispatch({ type: 'SET_LOADING', payload: { key: 'accounts', value: true } });
      const response = await emailAccountsAPI.getAll();
      dispatch({ type: 'SET_ACCOUNTS', payload: response.accounts });
      if (response.accounts.length > 0 && !state.selectedAccount) {
        dispatch({ type: 'SET_SELECTED_ACCOUNT', payload: response.accounts[0].id });
      }
    } catch (error) {
      console.error('Failed to load accounts:', error);
    } finally {
      dispatch({ type: 'SET_LOADING', payload: { key: 'accounts', value: false } });
    }
  }, [state.selectedAccount]);

  const loadFolders = useCallback(async (accountId: string) => {
    if (!accountId) return;
    
    try {
      dispatch({ type: 'SET_LOADING', payload: { key: 'folders', value: true } });
      const response = await emailAccountsAPI.getFolders(accountId);
      dispatch({ type: 'SET_FOLDERS', payload: response.folders });
      
      // 如果当前选中的文件夹不在列表中，选择第一个文件夹
      if (response.folders.length > 0) {
        const currentFolder = response.folders.find(f => f.normalized_name === state.selectedFolder);
        if (!currentFolder) {
          dispatch({ type: 'SET_SELECTED_FOLDER', payload: response.folders[0].normalized_name });
        }
      }
    } catch (error) {
      console.error('Failed to load folders:', error);
    } finally {
      dispatch({ type: 'SET_LOADING', payload: { key: 'folders', value: false } });
    }
  }, [state.selectedFolder]);

  const handleFolderSelect = useCallback(async (folderName: string) => {
    // 先设置选中的文件夹
    dispatch({ type: 'SET_SELECTED_FOLDER', payload: folderName });
    // 清空当前邮件列表
    dispatch({ type: 'SET_MESSAGES', payload: { messages: [], append: false } });
    dispatch({ type: 'SET_SELECTED_MESSAGE', payload: null });
    dispatch({ type: 'SET_PAGINATION', payload: { currentPage: 1, hasMore: true } });
    
    // 主动加载邮件（解决再次点击同一文件夹不刷新的问题）
    if (!state.selectedAccount) return;
    
    dispatch({ type: 'SET_LOADING', payload: { key: 'messages', value: true } });
    
    try {
      const response = await emailMessagesAPI.getAll({
        folder: folderName,
        account_id: state.selectedAccount,
        search: state.search || undefined,
        page: 1,
        per_page: 20,
      });
      
      dispatch({ 
        type: 'SET_MESSAGES', 
        payload: { messages: response.messages, append: false } 
      });
      
      dispatch({
        type: 'SET_PAGINATION',
        payload: { currentPage: 1, hasMore: response.pagination.has_next }
      });
      
    } catch (error) {
      console.error('Failed to load messages:', error);
      dispatch({ 
        type: 'SET_FETCH_MESSAGE', 
        payload: { type: 'error', text: '加载邮件失败' }
      });
    } finally {
      dispatch({ type: 'SET_LOADING', payload: { key: 'messages', value: false } });
    }
  }, [state.selectedAccount, state.search]);

  const loadMessages = useCallback(async (pageNum = 1, append = false) => {
    if (!state.selectedAccount) return;
    
    dispatch({ 
      type: 'SET_LOADING', 
      payload: { key: append ? 'moreMessages' : 'messages', value: true } 
    });
    
    try {
      const response = await emailMessagesAPI.getAll({
        folder: state.selectedFolder,
        account_id: state.selectedAccount,
        search: state.search || undefined,
        page: pageNum,
        per_page: 20,
      });
      
      dispatch({ 
        type: 'SET_MESSAGES', 
        payload: { messages: response.messages, append } 
      });
      
      dispatch({
        type: 'SET_PAGINATION',
        payload: { currentPage: pageNum, hasMore: response.pagination.has_next }
      });
      
    } catch (error) {
      console.error('Failed to load messages:', error);
      dispatch({ 
        type: 'SET_FETCH_MESSAGE', 
        payload: { type: 'error', text: '加载邮件失败' }
      });
    } finally {
      dispatch({ 
        type: 'SET_LOADING', 
        payload: { key: append ? 'moreMessages' : 'messages', value: false } 
      });
    }
  }, [state.selectedAccount, state.selectedFolder, state.search]);

  // 加载邮箱账号列表
  useEffect(() => {
    loadAccounts();
  }, [loadAccounts]);

  // 当选择账号时，加载文件夹列表
  useEffect(() => {
    if (state.selectedAccount) {
      loadFolders(state.selectedAccount);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state.selectedAccount]);

  // 当选择账号或文件夹时，加载邮件列表
  useEffect(() => {
    if (state.selectedAccount && state.selectedFolder) {
      loadMessages();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state.selectedAccount, state.selectedFolder]);

  // 防抖搜索
  const debouncedSearch = useMemo(
    () => {
      let timeoutId: number;
      return () => {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
          loadMessages(1, false);
        }, 500);
      };
    },
    [loadMessages]
  );

  useEffect(() => {
    if (state.selectedAccount && state.search) {
      debouncedSearch();
    }
  }, [state.search, state.selectedAccount, debouncedSearch]);

  const loadMoreMessages = () => {
    if (state.hasMore && !state.loading.moreMessages) {
      loadMessages(state.currentPage + 1, true);
    }
  };

  // 轮询检查拉取状态
  const pollFetchStatus = useCallback(async (accountId: string) => {
    const interval = setInterval(async () => {
      try {
        const status = await emailAccountsAPI.getFetchStatus(accountId);
        
        if (!status.is_fetching) {
          clearInterval(interval);
          showFetchMessage('success', '邮件拉取完成');
          
          // 刷新邮件列表
          if (state.selectedAccount === accountId && state.folder === 'inbox') {
            await loadMessages(1, false);
          }
        }
      } catch (error) {
        console.error('Failed to check fetch status:', error);
        clearInterval(interval);
      }
    }, 2000); // 每2秒检查一次
    
    // 设置超时，最多轮询5分钟
    setTimeout(() => {
      clearInterval(interval);
    }, 300000);
  }, [state.selectedAccount, state.folder, loadMessages, showFetchMessage]);

  const fetchLatestEmails = useCallback(async (accountId: string) => {
    if (isFetchingRef.current) {
        console.log('Already fetching emails, skipping...');
        showFetchMessage('info', '邮件正在拉取中，请稍后...');
        return;
    }
    
    try {
        isFetchingRef.current = true;
        dispatch({ type: 'SET_LOADING', payload: { key: 'fetching', value: true } });
        
        // 启动后台拉取任务
        const response = await emailAccountsAPI.fetchMessages(accountId);
        
        if (response.success) {
            showFetchMessage('success', response.message || '邮件拉取已启动');
            
            // 开始轮询检查状态
            pollFetchStatus(accountId);
        } else {
            showFetchMessage('error', '启动拉取失败');
        }
        
    } catch (error: unknown) {
        console.error('Failed to fetch emails:', error);
        
        const errorMessage = error instanceof Error ? error.message : '拉取邮件失败';
        
        if (errorMessage.includes('正在拉取中')) {
            showFetchMessage('info', '后台正在拉取邮件，请稍后刷新查看');
        } else {
            showFetchMessage('error', errorMessage);
        }
    } finally {
        isFetchingRef.current = false;
        dispatch({ type: 'SET_LOADING', payload: { key: 'fetching', value: false } });
    }
  }, [pollFetchStatus, showFetchMessage]);

  const handleSelectMessage = async (message: EmailMessage) => {
    dispatch({ type: 'SET_SELECTED_MESSAGE', payload: message });
    
    // 如果邮件未读，标记为已读
    if (!message.is_read) {
      try {
        await emailMessagesAPI.update(message.id, { is_read: true });
        dispatch({ type: 'UPDATE_MESSAGE', payload: { ...message, is_read: true } });
      } catch (error) {
        console.error('Failed to mark as read:', error);
      }
    }
    
    // 如果未加载完整内容，则按需加载
    if (!message.is_full_content) {
      try {
        const response = await emailMessagesAPI.loadBody(message.id);
        dispatch({ type: 'UPDATE_MESSAGE', payload: response.message });
      } catch (error) {
        console.error('Failed to load full message:', error);
      }
    }
  };

  const handleSendEmail = async () => {
    try {
      dispatch({ type: 'SET_LOADING', payload: { key: 'sendingEmail', value: true } });
      
      // 准备发送数据
      const sendData: {
        account_id: string;
        to: string;
        cc?: string;
        bcc?: string;
        subject: string;
        body: string;
        body_html?: string;
        attachments?: File[];
      } = {
        account_id: state.selectedAccount,
        to: composeData.to,
        subject: composeData.subject,
        body: composeData.body,
      };
      
      if (composeData.cc) sendData.cc = composeData.cc;
      if (composeData.bcc) sendData.bcc = composeData.bcc;
      if (composeData.isHtml && composeData.body_html) {
        sendData.body_html = composeData.body_html;
      }
      if (composeData.attachments.length > 0) {
        sendData.attachments = composeData.attachments;
      }
      
      await emailMessagesAPI.send(sendData);
      
      setIsComposeOpen(false);
      setComposeData({ 
        to: '', 
        cc: '', 
        bcc: '', 
        subject: '', 
        body: '', 
        body_html: '',
        isHtml: false,
        attachments: []
      });
      showFetchMessage('success', '邮件发送成功');
    } catch (error: unknown) {
      console.error('Failed to send email:', error);
      showFetchMessage('error', error instanceof Error ? error.message : '邮件发送失败');
    } finally {
      dispatch({ type: 'SET_LOADING', payload: { key: 'sendingEmail', value: false } });
    }
  };

  const currentFolder = state.folders.find((f) => f.normalized_name === state.selectedFolder);

  return (
    <>
      <div className="flex h-[calc(100vh-7rem)] overflow-hidden">
        {/* 左侧边栏 - 邮箱账号和文件夹 */}
        <div className="w-48 border-r bg-muted/50 flex-shrink-0">
          <div className="p-3">
            <h2 className="text-sm font-semibold mb-2 px-2">邮箱账号</h2>
            <Select value={state.selectedAccount} onValueChange={(value) => dispatch({ type: 'SET_SELECTED_ACCOUNT', payload: value })}>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="选择邮箱" />
              </SelectTrigger>
              <SelectContent>
                {state.accounts.map((account) => (
                  <SelectItem key={account.id} value={account.id}>
                    {account.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          
          <Separator />
          
          <div className="p-3">
            <h2 className="text-sm font-semibold mb-2 px-2">文件夹</h2>
            <div className="space-y-1">
              {state.loading.folders ? (
                <div className="flex items-center justify-center py-4">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  <span className="ml-2 text-sm text-muted-foreground">加载中...</span>
                </div>
              ) : (
                state.folders.map((folder) => {
                  // 根据文件夹类型选择图标
                  const getFolderIcon = (normalizedName: string) => {
                    switch (normalizedName) {
                      case 'inbox': return Inbox;
                      case 'sent': return Send;
                      case 'drafts': return File;
                      case 'trash': return Trash2;
                      case 'junk': return AlertCircle;
                      default: return Mail;
                    }
                  };
                  
                  const Icon = getFolderIcon(folder.normalized_name);
                  return (
                    <Button
                      key={folder.normalized_name}
                      variant={state.selectedFolder === folder.normalized_name ? 'secondary' : 'ghost'}
                      className="w-full justify-start"
                      onClick={() => handleFolderSelect(folder.normalized_name)}
                    >
                      <Icon className="mr-2 h-4 w-4" />
                      <span className="flex-1 text-left">{folder.name}</span>
                      {folder.email_count > 0 && (
                        <Badge variant="secondary" className="ml-2 text-xs">
                          {folder.email_count}
                        </Badge>
                      )}
                    </Button>
                  );
                })
              )}
            </div>
          </div>
        </div>

        {/* 中间邮件列表 */}
        <div className="w-80 border-r bg-background flex-shrink-0 flex flex-col h-full">
          <div className="p-4 border-b">
            <div className="flex items-center justify-between mb-2">
              <h2 className="text-lg font-semibold">{currentFolder?.name}</h2>
              <div className="flex gap-1">
                <Button variant="outline" size="sm" onClick={() => setIsComposeOpen(true)}>
                  <Plus className="h-4 w-4" />
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => fetchLatestEmails(state.selectedAccount)}
                  disabled={state.loading.fetching}
                  title={state.loading.fetching ? "正在拉取邮件..." : "刷新邮件"}
                >
                  {state.loading.fetching ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
                </Button>
              </div>
            </div>
            
            {/* 消息提示 */}
            {state.fetchMessage && (
              <Alert 
                className={`mb-2 ${
                  state.fetchMessage.type === 'error' ? 'border-destructive bg-destructive/10' : 
                  state.fetchMessage.type === 'success' ? 'border-green-500 bg-green-50 dark:bg-green-950' : 
                  'border-blue-500 bg-blue-50 dark:bg-blue-950'
                }`}
              >
                {state.fetchMessage.type === 'error' ? (
                  <AlertCircle className="h-4 w-4 text-destructive" />
                ) : state.fetchMessage.type === 'success' ? (
                  <CheckCircle className="h-4 w-4 text-green-600" />
                ) : (
                  <Info className="h-4 w-4 text-blue-600" />
                )}
                <AlertDescription className="text-sm ml-2">
                  {state.fetchMessage.text}
                </AlertDescription>
              </Alert>
            )}
            
            <Input
              placeholder="搜索邮件..."
              value={state.search}
              onChange={(e) => dispatch({ type: 'SET_SEARCH', payload: e.target.value })}
              className="w-full"
            />
          </div>
          
          <div className="flex-1 overflow-y-auto">
            {state.loading.messages ? (
              <div className="flex items-center justify-center h-32">
                <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              </div>
            ) : state.messages.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-32 text-muted-foreground">
                <Mail className="h-8 w-8 mb-2" />
                <p className="text-sm">没有邮件</p>
              </div>
            ) : (
              <>
                {state.messages.map((message) => (
                  <div
                    key={message.id}
                    className={`p-3 border-b cursor-pointer hover:bg-muted/50 transition-colors ${
                      state.selectedMessage?.id === message.id ? 'bg-muted' : ''
                    } ${!message.is_read ? 'font-semibold' : ''}`}
                    onClick={() => handleSelectMessage(message)}
                  >
                    <div className="flex items-start justify-between mb-1">
                      <span className="text-sm truncate flex-1">
                        {message.sender || '未知发件人'}
                      </span>
                      <span className="text-xs text-muted-foreground ml-2">
                        {message.received_at 
                          ? new Date(message.received_at).toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
                          : '未知'}
                      </span>
                    </div>
                    <div className="flex items-center gap-2 mb-1">
                      <p className="text-sm truncate flex-1">
                        {message.subject || '(无主题)'}
                      </p>
                      {message.attachments && message.attachments.length > 0 && (
                        <Paperclip className="h-3 w-3 text-muted-foreground" />
                      )}
                    </div>
                    <p className="text-xs text-muted-foreground truncate">
                      {message.body_text || '(无内容)'}
                    </p>
                  </div>
                ))}
                
                {state.hasMore && (
                  <div className="p-4 text-center">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={loadMoreMessages}
                      disabled={state.loading.moreMessages}
                    >
                      {state.loading.moreMessages ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          加载中...
                        </>
                      ) : (
                        '加载更多'
                      )}
                    </Button>
                  </div>
                )}
              </>
            )}
          </div>
        </div>

        {/* 右侧邮件详情 */}
        <div className="flex-1 bg-background flex flex-col h-full">
          {state.selectedMessage ? (
            <>
              <div className="p-6 border-b">
                <h1 className="text-2xl font-bold mb-4">
                  {state.selectedMessage.subject || '(无主题)'}
                </h1>
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm">
                    <span className="text-muted-foreground">发件人:</span>
                    <span>{state.selectedMessage.sender || '未知'}</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <span className="text-muted-foreground">收件人:</span>
                    <span>
                      {Array.isArray(state.selectedMessage.recipients) 
                        ? state.selectedMessage.recipients.join(', ') 
                        : state.selectedMessage.recipients || '未知'}
                    </span>
                  </div>
                  {state.selectedMessage.cc && state.selectedMessage.cc.length > 0 && (
                    <div className="flex items-center gap-2 text-sm">
                      <span className="text-muted-foreground">抄送:</span>
                      <span>
                        {Array.isArray(state.selectedMessage.cc) 
                          ? state.selectedMessage.cc.join(', ') 
                          : state.selectedMessage.cc}
                      </span>
                    </div>
                  )}
                  <div className="flex items-center gap-2 text-sm">
                    <span className="text-muted-foreground">时间:</span>
                    <span>
                      {state.selectedMessage.received_at 
                        ? new Date(state.selectedMessage.received_at).toLocaleString('zh-CN')
                        : '未知'}
                    </span>
                  </div>
                </div>
              </div>
              <div className="flex-1 overflow-y-auto p-6">
                {/* AI总结按钮 */}
                <div className="mb-4 flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Button
                      onClick={handleAiSummary}
                      disabled={state.loading.aiSummarizing}
                      variant="outline"
                      size="sm"
                      className="flex items-center gap-2"
                    >
                      {state.loading.aiSummarizing ? (
                        <Loader2 className="h-4 w-4 animate-spin" />
                      ) : (
                        <Sparkles className="h-4 w-4" />
                      )}
                      {state.loading.aiSummarizing ? 'AI总结中...' : 'AI总结'}
                    </Button>
                  </div>
                </div>

                {/* 邮件正文内容 */}
                {state.selectedMessage.body_html ? (
                  <div 
                    className="prose max-w-none"
                    dangerouslySetInnerHTML={{ 
                      __html: DOMPurify.sanitize(state.selectedMessage.body_html, {
                        ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'u', 'a', 'img', 'div', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'blockquote', 'pre', 'code'],
                        ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'style', 'class']
                      })
                    }}
                  />
                ) : (
                  <pre className="whitespace-pre-wrap font-sans">
                    {state.selectedMessage.body_text || '(无内容)'}
                  </pre>
                )}
                
                {state.selectedMessage.attachments && state.selectedMessage.attachments.length > 0 && (
                  <div className="mt-6 pt-6 border-t">
                    <h3 className="text-sm font-semibold mb-3">附件</h3>
                    <div className="space-y-2">
                      {state.selectedMessage.attachments.map((attachment: unknown, index: number) => (
                        <div key={index} className="flex items-center gap-2 p-2 border rounded">
                          <Paperclip className="h-4 w-4" />
                          <span className="text-sm">{(attachment as { filename: string }).filename}</span>
                          <Badge variant="outline" className="ml-auto">
                            {(attachment as { size: string }).size}
                          </Badge>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </>
          ) : (
            <div className="flex items-center justify-center h-full text-muted-foreground">
              <div className="text-center">
                <Mail className="h-16 w-16 mx-auto mb-4 opacity-50" />
                <p>选择一封邮件查看详情</p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 写邮件对话框 */}
      <Dialog open={isComposeOpen} onOpenChange={setIsComposeOpen}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>写邮件</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label htmlFor="to">收件人 *</Label>
              <Input
                id="to"
                value={composeData.to}
                onChange={(e) => setComposeData({ ...composeData, to: e.target.value })}
                placeholder="recipient@example.com (多个收件人用逗号分隔)"
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="cc">抄送 (CC)</Label>
                <Input
                  id="cc"
                  value={composeData.cc}
                  onChange={(e) => setComposeData({ ...composeData, cc: e.target.value })}
                  placeholder="cc@example.com"
                />
              </div>
              <div>
                <Label htmlFor="bcc">密送 (BCC)</Label>
                <Input
                  id="bcc"
                  value={composeData.bcc}
                  onChange={(e) => setComposeData({ ...composeData, bcc: e.target.value })}
                  placeholder="bcc@example.com"
                />
              </div>
            </div>
            <div>
              <Label htmlFor="subject">主题 *</Label>
              <Input
                id="subject"
                value={composeData.subject}
                onChange={(e) => setComposeData({ ...composeData, subject: e.target.value })}
                placeholder="邮件主题"
              />
            </div>
            <div>
              <div className="flex items-center justify-between mb-2">
                <Label htmlFor="body">正文 *</Label>
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  onClick={() => setComposeData({ ...composeData, isHtml: !composeData.isHtml })}
                  className="text-xs"
                >
                  {composeData.isHtml ? '切换到纯文本' : '切换到HTML'}
                </Button>
              </div>
              <Textarea
                id="body"
                value={composeData.isHtml ? composeData.body_html : composeData.body}
                onChange={(e) => {
                  if (composeData.isHtml) {
                    setComposeData({ ...composeData, body_html: e.target.value, body: e.target.value.replace(/<[^>]*>/g, '') });
                  } else {
                    setComposeData({ ...composeData, body: e.target.value });
                  }
                }}
                placeholder={composeData.isHtml ? "HTML邮件正文（支持HTML标签）" : "邮件正文"}
                rows={12}
                className="font-mono text-sm"
              />
              {composeData.isHtml && (
                <p className="text-xs text-muted-foreground mt-1">
                  HTML模式：支持 &lt;p&gt;, &lt;br&gt;, &lt;strong&gt;, &lt;em&gt;, &lt;a&gt; 等标签
                </p>
              )}
            </div>
            
            {/* 附件上传区域 */}
            <div>
              <Label>附件</Label>
              <div className="mt-2 space-y-2">
                <div className="flex items-center gap-2">
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      const input = document.createElement('input');
                      input.type = 'file';
                      input.multiple = true;
                      input.onchange = (e) => {
                        const files = Array.from((e.target as HTMLInputElement).files || []);
                        setComposeData(prev => ({
                          ...prev,
                          attachments: [...prev.attachments, ...files]
                        }));
                      };
                      input.click();
                    }}
                  >
                    <Upload className="h-4 w-4 mr-2" />
                    选择文件
                  </Button>
                  {composeData.attachments.length > 0 && (
                    <span className="text-sm text-muted-foreground">
                      已选择 {composeData.attachments.length} 个文件
                    </span>
                  )}
                </div>
                
                {/* 附件列表 */}
                {composeData.attachments.length > 0 && (
                  <div className="space-y-2 max-h-32 overflow-y-auto border rounded-md p-2">
                    {composeData.attachments.map((file, index) => (
                      <div key={index} className="flex items-center justify-between bg-muted/50 p-2 rounded">
                        <div className="flex items-center gap-2 flex-1 min-w-0">
                          <Paperclip className="h-4 w-4 flex-shrink-0" />
                          <span className="text-sm truncate">{file.name}</span>
                          <Badge variant="outline" className="text-xs flex-shrink-0">
                            {(file.size / 1024).toFixed(1)} KB
                          </Badge>
                        </div>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setComposeData(prev => ({
                              ...prev,
                              attachments: prev.attachments.filter((_, i) => i !== index)
                            }));
                          }}
                          className="ml-2 flex-shrink-0"
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
            
            <div className="flex justify-end gap-2 pt-4 border-t">
              <Button variant="outline" onClick={() => setIsComposeOpen(false)}>
                取消
              </Button>
              <Button 
                onClick={handleSendEmail} 
                disabled={state.loading.sendingEmail || !composeData.to || !composeData.subject || !composeData.body}
              >
                {state.loading.sendingEmail ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    发送中...
                  </>
                ) : (
                  <>
                    <Send className="mr-2 h-4 w-4" />
                    发送
                  </>
                )}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* AI总结对话框 */}
      <Sheet open={showAiSummary} onOpenChange={setShowAiSummary}>
        <SheetContent side="right" className="w-[800px] sm:max-w-none max-h-[100vh] overflow-hidden flex flex-col">
          <SheetHeader>
            <div className="flex items-center gap-2">
              <Sparkles className="h-5 w-5 text-blue-600 dark:text-blue-400" />
              <SheetTitle>AI邮件总结</SheetTitle>
            </div>
          </SheetHeader>
          
          <div className="flex-1 overflow-y-auto">
            {aiSummary ? (
              <div className="space-y-4">
                {/* 邮件信息卡片 */}
                <div className="rounded-lg border bg-muted/50 p-4">
                  <div className="grid gap-2 text-sm">
                    <div className="flex items-start gap-2">
                      <span className="font-semibold text-muted-foreground min-w-16">主题:</span>
                      <span className="flex-1">{state.selectedMessage?.subject}</span>
                    </div>
                    <div className="flex items-start gap-2">
                      <span className="font-semibold text-muted-foreground min-w-16">发件人:</span>
                      <span className="flex-1">{state.selectedMessage?.sender}</span>
                    </div>
                    <div className="flex items-start gap-2">
                      <span className="font-semibold text-muted-foreground min-w-16">时间:</span>
                      <span className="flex-1">
                        {state.selectedMessage?.received_at 
                          ? new Date(state.selectedMessage.received_at).toLocaleString('zh-CN')
                          : '未知'}
                      </span>
                    </div>
                  </div>
                </div>

                {/* AI总结内容 */}
                <div className="rounded-lg border bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-blue-950/20 dark:to-indigo-950/20 p-6">
                  <div className="prose prose-sm dark:prose-invert max-w-none
                    prose-headings:text-foreground
                    prose-h1:text-2xl prose-h1:font-bold prose-h1:mb-4
                    prose-h2:text-xl prose-h2:font-semibold prose-h2:mt-6 prose-h2:mb-3
                    prose-h3:text-lg prose-h3:font-semibold prose-h3:mt-4 prose-h3:mb-2
                    prose-p:text-foreground prose-p:leading-relaxed prose-p:my-2
                    prose-ul:my-3 prose-li:my-1.5 prose-li:text-foreground
                    prose-ol:my-3 prose-ol:text-foreground
                    prose-strong:text-foreground prose-strong:font-semibold
                    prose-em:text-foreground
                    prose-blockquote:border-l-blue-500 prose-blockquote:text-foreground
                    prose-code:text-foreground prose-code:bg-muted prose-code:px-1 prose-code:py-0.5 prose-code:rounded
                    prose-pre:bg-muted prose-pre:text-foreground
                    [&>*:first-child]:mt-0
                    [&>*:last-child]:mb-0">
                    <ReactMarkdown remarkPlugins={[remarkGfm]}>
                      {aiSummary}
                    </ReactMarkdown>
                  </div>
                </div>

                {/* 操作按钮 */}
                <div className="flex justify-between items-center pt-4 border-t">
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={handleRegenerateSummary}
                      disabled={state.loading.aiSummarizing}
                      className="flex items-center gap-2"
                    >
                      {state.loading.aiSummarizing ? (
                        <Loader2 className="h-4 w-4 animate-spin" />
                      ) : (
                        <RotateCcw className="h-4 w-4" />
                      )}
                      重新生成
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={handleClearSummary}
                      disabled={state.loading.aiSummarizing}
                      className="flex items-center gap-2 text-red-600 hover:text-red-700 hover:border-red-300"
                    >
                      <Trash className="h-4 w-4" />
                      清空
                    </Button>
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        navigator.clipboard.writeText(aiSummary);
                        showFetchMessage('success', '总结已复制到剪贴板');
                      }}
                    >
                      复制总结
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setShowAiSummary(false)}
                    >
                      关闭
                    </Button>
                  </div>
                </div>
              </div>
            ) : (
              <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                <Sparkles className="h-12 w-12 mb-4 opacity-50" />
                <p>暂无总结内容</p>
              </div>
            )}
          </div>
        </SheetContent>
      </Sheet>
    </>
  );
}